package com.wanshi.utils;


import java.io.*;
import java.lang.reflect.Method;

@SuppressWarnings("all")
public class DatiOutThread extends Thread{

    private String result;
    public String getResult() {
        return result;
    }

    private String name;
    private String method;
    private Object[] objs;


    public DatiOutThread(String name, String method, Object[] objs){
        this.name = name;
        this.method = method;
        this.objs =objs;
    };

    @Override
    public void run() {
        PrintStream oldStream = null;
        ByteArrayOutputStream baoStream = null;
        try{
            oldStream = System.out;
            baoStream = new ByteArrayOutputStream(1024);
            PrintStream cacheStream = new PrintStream(baoStream);
            System.setOut(cacheStream);//不打印到控制台

            Class c = Class.forName(name);
            Method[] ms = c.getMethods();
            for (Method m:ms) {
                if(m.getName().equals(method)){
                    m.invoke(c.getDeclaredConstructor().newInstance(), objs);
                    System.setOut(oldStream);
                    result = baoStream.toString();
                    break;
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(oldStream != null){
                oldStream.close();
            }
            if(baoStream != null){
                try {
                    baoStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
